<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    /**

     * * S打散依次推入栈中，栈 stack 只存放'('，如果是左括号就 stack.push(')')，
     同时次数 +1，如果是右括号，就判断 stack.length，如果仍然有'('就出栈，否则次数+1
     */
    const minAddToMakeValid = function (S) {
      const stack = []
      let time = 0
      for (let s of S) {
        if (s === '(') {
          stack.push('(')
          time++
        } else {
          if (stack.length) {
            stack.pop()
            time--
          } else {
            time++
          }
        }
      }
      return time
    };
    console.log(minAddToMakeValid(s = "())"))
  </script>
</body>

</html>